package org.gntc.prayer.myprayer;

import org.gntc.prayer.R;
import org.gntc.prayer.db.PrayerDBMngr;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;

public class AnswerEditActivity extends Activity
{
	/** Called when the activity is first created. */
	
	private boolean			m_bEditMode;
	private int 				m_nPrayerID;
	private int 				m_nAnswerID;
	private PrayerDBMngr m_PrayerDBMngr;
	private EditText 			m_etAnswer;
		
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.answer_edit);
	    
	    // Parameter 설정
	    Intent intent = getIntent();
	    Bundle extra = intent.getExtras();
	    
	    if (extra != null)
	    {
	    	m_bEditMode = extra.getBoolean("edit_mode");		// Edit mode
	    	m_nPrayerID = extra.getInt("prayer_id");					// Prayer id
	    	m_nAnswerID = extra.getInt("answer_id");				// Answer id
	    }
	    else
	    {
	    	// Parameter 없으므로 Activity 종료
	    	Toast.makeText(AnswerEditActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
	    	finish();
	    }
	    
	    // 컨트롤 설정
	    m_etAnswer = (EditText) findViewById(R.id.edit_answer_prayer);
	    
	    // DB open
	    openDB();
	}
	
	/**
	 * onResume
	 */
	@Override
	public void onResume()
	{
		super.onResume();
		
		if (m_bEditMode)
		{
			// Answer 정보 가져오기
		    getAnswerInfo();
		}
	}
	
	/**
	 * onDestroy
	 */
	@Override
	public void onDestroy()
	{
		super.onDestroy();
		
		// DB close
		m_PrayerDBMngr.close();
	}
	
	/**
	 * Menu
	 */
	@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	getMenuInflater().inflate(R.menu.answer_edit_menu, menu);
    	return true;
    }
	
	/**
	 * Menu selected
	 */
	@Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch( item.getItemId() )
    	{
    	case R.id.answer_edit_btn_save :
    		if (m_bEditMode)
			{
				// 수정
				if (m_etAnswer.getText().length() == 0)
				{
					Toast.makeText(AnswerEditActivity.this, R.string.add_answer, Toast.LENGTH_SHORT).show();
					m_etAnswer.requestFocus();
				}
				else
				{
					m_PrayerDBMngr.updateAnswer(m_nAnswerID, m_etAnswer.getText().toString());
					Toast.makeText(AnswerEditActivity.this, R.string.answer_saved, Toast.LENGTH_SHORT).show();
					finish();
				}
			}
			else
			{
				// 추가
				boolean bVal = false;
				
				// Save answer
				bVal = saveAnswer();
				
				if (bVal)
				{
					// Toast
					Toast.makeText(AnswerEditActivity.this, R.string.answer_saved, Toast.LENGTH_SHORT).show();
					
					// Finish Activity
					finish();
				}
			}
    		break;
    		
    	case R.id.answer_edit_btn_cancel :
    		finishActivity();
    		break;
    		
    	default :
    		return false;
    	}
    	
    	return true;
    }
	
	/**
	 * DB 초기화
	 */
	private void openDB()
	{
		m_PrayerDBMngr = new PrayerDBMngr(AnswerEditActivity.this);
		
		try
		{
			m_PrayerDBMngr.open();
		}
		catch (SQLiteException e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * Save answer
	 * @return
	 */
	public boolean saveAnswer()
	{
		// Answer 내용 검사
		if (m_etAnswer.length() == 0)
		{
			Toast.makeText(AnswerEditActivity.this, R.string.add_answer, Toast.LENGTH_SHORT).show();
			m_etAnswer.requestFocus();
			return false;
		}
		
		long lRet = m_PrayerDBMngr.insertAnswer(m_nPrayerID, m_etAnswer.getText().toString());
		
		if (lRet == -1)
		{
			Toast.makeText(AnswerEditActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
			finish();
			return false;
		}
		
		return true;
	}
	
	/**
	 * Get answer
	 */
	public void getAnswerInfo()
	{
		// Answer 내용 설정
		String strAnswer = m_PrayerDBMngr.selectAnswerInfo(m_nAnswerID);
		m_etAnswer.setText(strAnswer);
		
		// 커서를 마지막으로 이동
		m_etAnswer.setSelection(m_etAnswer.length());	
	}
	
	/**
	 * Activity 종료
	 */
	private void finishActivity()
	{
		if (m_etAnswer.getText().toString().length() == 0)
		{
			// 입력 사항이 없으면 바로 Activity 종료
			finish();
		}
		else
		{
			// Yes, No 팝업에서 Yse 선택 시 Activity 종료
			DialogInterface.OnClickListener m_onClickListener_btnYes = new DialogInterface.OnClickListener()
			{
				public void onClick(DialogInterface dialog, int which)
				{
					finish();
				}
			};
			
			// 입력 사항이 있으면 팝업 창 표시
			AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
			
			alt_bld
			.setTitle(R.string.discard_changes)
			.setMessage(R.string.discard_changes_q).setCancelable(false)
			.setPositiveButton(R.string.yes, m_onClickListener_btnYes)
	        .setNegativeButton(R.string.no, null);
			
			AlertDialog altDlg = alt_bld.create();
			altDlg.setCancelable(true);
			altDlg.show();
		}
	}
	
	/**
	 * Back 키 이벤트 처리
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			finishActivity();
		}
		
		return false;
	}

}
